package com.ddd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ddd.domain.LoginUser;
import com.ddd.entity.User;
import com.ddd.mapper.MenuMapper;
import com.ddd.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(wrapper);

        if (Objects.isNull(user)){
            throw new RuntimeException("用户不存在");
        }

        //List<String> list = new ArrayList<>();
        //list.add("test");
        //list.add("admin");
        List<String> list = menuMapper.selectPermsByUserId(user.getId());
        // 把数据封装程UserDetails返回
        return new LoginUser(user , list);
    }
}
